<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称">
        <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="queryParams.describe" placeholder="请输入描述" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="queryParams.sign" placeholder="请输入标识" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="地图展示">
        <el-select v-model="queryParams.onmap" clearable placeholder="请选择">
          <el-option label="关闭" value="0"></el-option>
          <el-option label="开启" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['manager:category:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['manager:category:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['manager:category:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['manager:category:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="标识" align="center" prop="sign" />
      <el-table-column label="描述" align="center" prop="describe" />
      <el-table-column label="地图展示" align="center" prop="describe">
        <template slot-scope="scope">
          {{ scope.row.onmap === '1' ? '开启' : '关闭' }}
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.imgHref" :src="imgUrl(scope.row.imgHref)" alt="" width="25" height="25" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['manager:category:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['manager:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改基础分类管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="标识" prop="sign">
          <el-input v-model="form.sign" placeholder="请输入标识" />
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input v-model="form.describe" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="地图展示" prop="onmap">
          <el-switch v-model="form.onmap" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="属性">
          <div v-for="(item, index) in form.attrlist" v-bind:key="index" style="display:flex; margin-bottom:20px;">
            <el-form-item :prop="'attrlist.' + index + '.key'" :rules="{ validator: validatePass, trigger: 'blur' }">
              <el-input v-model="item.key" placeholder="请输入key" :disabled="item.state" :prop="form.attrlist[index].key" />
            </el-form-item>
            <el-form-item style="margin:0 5px" :prop="'attrlist.' + index + '.value'" :rules="{ required: true, message: 'value不能为空', trigger: 'blur' }">
              <el-input v-model="item.value" :disabled="item.state" placeholder="请输入value" />
            </el-form-item>
            <el-button v-if="index == 0" @click="addTo" type="primary" icon="el-icon-circle-plus-outline"></el-button>
            <!-- + -->
            <el-button v-if="index > 2" @click="deleteIndex(index)" type="primary" icon="el-icon-remove-outline"></el-button>
            <!-- - -->
            <div v-if="matchState(index)" style="width:65px;height:36px;"></div>
          </div>
        </el-form-item>

        <el-form-item label="图标" prop="imgHref">
          <el-upload class="avatar-uploader" :before-upload="beforeAvatarUpload" :action="uploadImgUrl" :show-file-list="false" :headers="headers" :on-success="handleUploadSuccess" :on-error="handleUploadError">
            <i v-if="imageUrl" class="el-icon-circle-close imgsty" @click.stop="deleteImg"></i>
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory } from '@/api/basicInfo/category';
import { getToken } from '@/utils/auth';
export default {
  name: 'Category',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      NameList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 基础分类管理表格数据
      categoryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryName: null,
        describe: null,
        onmap: '',
        sign: ''
      },
      // 表单参数
      form: {
        attrlist: []
      },
      // 表单校验
      rules: {
        categoryName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        describe: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        imgHref: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        sign: [
          { required: true, message: '请输入标识符', trigger: 'blur' },
          {
            pattern: /[a-zA-Z]/i,
            message: '标识值必须为英文',
            trigger: 'blur'
          }
        ]
      },
      // 自定义表单验证
      validatePass: (rule, value, callback) => {
        console.log(/[a-zA-Z]/i.test(value));
        if (!value) {
          callback(new Error('请输入key值'));
        } else if (!/[a-zA-Z]/i.test(value)) {
          callback('key值必须为英文字母');
        }

        // 判断是否有重复的数据
        let list = rule.field.split('.');
        for (let i = 0; i < this.form.attrlist.length; i++) {
          console.log(this.form.attrlist[i].key);
          if (this.form.attrlist[i].key == value && list[1] != i) {
            return callback('key值不能重复');
            break;
          }
        }

        callback();
      },

      // 图片上传配置
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/file/common/upload', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      imgurl: process.env.VUE_APP_BASE_IMG,
      imageUrl: ''
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询基础分类管理列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        console.log(response);
        this.categoryList = response.rows;
        console.log(response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryName: null,
        imgHref: null,
        describe: null,
        spare: null,
        attrlist: []
      };
      this.imageUrl = '';
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.NameList = selection.map(item => item.categoryName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加基础分类管理';

      console.log(this.form);

      this.form.attrlist.push(
        {
          key: 'name',
          value: '名称',
          state: true
        },
        {
          key: 'lng',
          value: '经度',
          state: true
        },
        {
          key: 'lat',
          value: '纬度',
          state: true
        }
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCategory(id).then(response => {
        this.form = response.data;
        this.form.attrlist[0].state = true;
        this.form.attrlist[1].state = true;
        this.form.attrlist[2].state = true;

        // 图片
        if (response.data.imgHref) {
          this.imageUrl = this.imgurl + response.data.imgHref;
        }

        this.open = true;
        this.title = '修改基础分类管理';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.open = false;
              this.imageUrl = '';
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.categoryName || this.NameList;
      this.$confirm('是否确认删除基础分类名称为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delCategory(row.id || this.ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有基础分类管理数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return exportCategory(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    addTo() {
      console.log(1);
      this.form.attrlist.push({
        key: '',
        val: ''
      });
    },
    deleteIndex(index) {
      console.log(2);
      this.form.attrlist.splice(index, 1);
    },
    imgUrl(data) {
      if (data) {
        return this.imgurl + data;
      }
      return '';
    },
    //对上传图片的大小、格式进行限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isJPG2 = file.type === 'image/jpg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 1;
      if (!isJPG && !isJPG2 && !isPNG) {
        this.$message.warning('只支持jpg或png格式图片');
      }
      if (!isLt5M) {
        this.$message.warning('请上传1MB以内的图片!');
      }
      return (isJPG || isJPG2 || isPNG) && isLt5M;
    },
    // 上传成功
    handleUploadSuccess(res) {
    	console.log(res.url)
      this.imageUrl = this.imgurl + res.url;
      this.form.imgHref = res.fileName;
    },
    // 上传失败
    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      });
    },
    // 删除图片
    deleteImg() {
      this.imageUrl = null;
      this.form.imgHref = '';
    },
    // 判断是否占位
    matchState(index) {
      console.log(index);
      if (index == 1 || index == 2) {
        return true;
      } else {
        return false;
      }
    }
  },
  // 过滤器
  filters: {}
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  /* overflow: hidden; */
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  width: 50px;
  height: 50px;
  display: block;
}

.imgsty {
  position: absolute;
  top: -5px;
  right: -5px;
  background: red;
  /* padding: 4px; */
  color: #fff;
  border-radius: 10px;
}
</style>
